package wifi.source;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

/**
 * 
 * @author George Oprina
 * 
 *         08.06.2011
 */

public class ScanWifi extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Functions.makeToast("Scan Wifi", this);
		scan();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, Menu.NONE, "Back");
		menu.add(0, 2, Menu.NONE, "Scan");
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case (1):
			Intent get_back = new Intent();
			get_back.setClass(this, WiFiCon.class);
			startActivity(get_back);
			finish();
			break;
		case (2):
			scan();
			break;
		}

		return true;
	}

	public void scan() {
		WifiManager wifi_manager = (WifiManager) this
				.getSystemService(WIFI_SERVICE);

		// enable wi-fi
		if (!wifi_manager.isWifiEnabled()) {
			Functions.makeToast("Enable WiFi", this);
			wifi_manager.setWifiEnabled(true);
			while (!wifi_manager.isWifiEnabled()) {
				Functions.sleep(300);
			}
		}
		
		//scan for AP's in the area
		if (wifi_manager.startScan()) {

			List<ScanResult> res = wifi_manager.getScanResults();
			while (res == null) {
				Functions.sleep(300);
			}
			Functions.makeToast("Scanning Wi-Fi", this);
			String result = "";
			for (ScanResult s : res) {
				String str = s.SSID + " -> level: " + s.level;
				result += str + "\n";
			}
			// MyTextView text = new MyTextView(this, result);
			setContentView(Functions.makeTextView(result, this));
		}
	}
}
